{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Predicting the video"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Requirements: \n",
    "tensorflow==2.3.0\n",
    "keras==2.4.3\n",
    "scikit-learn==0.23.2\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'4.5.1'"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cv2.__version__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.models import load_model\n",
    "from collections import deque\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import argparse\n",
    "import pickle\n",
    "import cv2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#WORKING PROJECT\n",
    "import numpy as np\n",
    "import argparse\n",
    "import pickle\n",
    "import cv2\n",
    "import os\n",
    "import time \n",
    "from keras.models import load_model\n",
    "from collections import deque\n",
    "\n",
    "def print_results(video, limit=None):\n",
    "        #fig=plt.figure(figsize=(16, 30))\n",
    "        if not os.path.exists('output'):\n",
    "            os.mkdir('output')\n",
    "\n",
    "        print(\"Loading model ...\")\n",
    "        model = load_model('model/model.h5')\n",
    "        Q = deque(maxlen=128)\n",
    "        vs = cv2.VideoCapture(video)\n",
    "        writer = None\n",
    "        (W, H) = (None, None)\n",
    "        count = 0     \n",
    "        while True:\n",
    "            # read the next frame from the file\n",
    "            (grabbed, frame) = vs.read()\n",
    "\n",
    "            # if the frame was not grabbed, then we have reached the end\n",
    "            # of the stream\n",
    "            if not grabbed:\n",
    "                break\n",
    "            \n",
    "            # if the frame dimensions are empty, grab them\n",
    "            if W is None or H is None:\n",
    "                (H, W) = frame.shape[:2]\n",
    "\n",
    "            # clone the output frame, then convert it from BGR to RGB\n",
    "            # ordering, resize the frame to a fixed 128x128, and then\n",
    "            # perform mean subtraction\n",
    "\n",
    "            \n",
    "            output = frame.copy()\n",
    "           \n",
    "            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n",
    "            frame = cv2.resize(frame, (128, 128)).astype(\"float32\")\n",
    "            frame = frame.reshape(128, 128, 3) / 255\n",
    "\n",
    "            # make predictions on the frame and then update the predictions\n",
    "            # queue\n",
    "            preds = model.predict(np.expand_dims(frame, axis=0))[0]\n",
    "#             print(\"preds\",preds)\n",
    "            Q.append(preds)\n",
    "\n",
    "            # perform prediction averaging over the current history of\n",
    "            # previous predictions\n",
    "            results = np.array(Q).mean(axis=0)\n",
    "            i = (preds > 0.50)[0]\n",
    "            label = i\n",
    "\n",
    "            text_color = (0, 255, 0) # default : green\n",
    "\n",
    "            if label: # Violence prob\n",
    "                text_color = (0, 0, 255) # red\n",
    "\n",
    "            else:\n",
    "                text_color = (0, 255, 0)\n",
    "\n",
    "            text = \"Violence: {}\".format(label)\n",
    "            FONT = cv2.FONT_HERSHEY_SIMPLEX \n",
    "\n",
    "            cv2.putText(output, text, (35, 50), FONT,1.25, text_color, 3) \n",
    "\n",
    "            # check if the video writer is None\n",
    "            if writer is None:\n",
    "                # initialize our video writer\n",
    "                fourcc = cv2.VideoWriter_fourcc(*\"MJPG\")\n",
    "                writer = cv2.VideoWriter(\"output/v_output.avi\", fourcc, 30,(W, H), True)\n",
    "\n",
    "            # write the output frame to disk\n",
    "            writer.write(output)\n",
    "\n",
    "            # show the output image\n",
    "            cv2.imshow(\"Output\", output)\n",
    "            key = cv2.waitKey(1) & 0xFF\n",
    "\n",
    "            # if the `q` key was pressed, break from the loop\n",
    "            if key == ord(\"q\"):\n",
    "                break\n",
    "        # release the file pointersq\n",
    "        print(\"[INFO] cleaning up...\")\n",
    "        writer.release()\n",
    "        vs.release()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "V_path = \"video/violence_1/V_57.mp4\"  \n",
    "NV_path = \"video/non_violence/NV_25.mp4\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading model ...\n",
      "[INFO] cleaning up...\n"
     ]
    }
   ],
   "source": [
    "print_results(V_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# END"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
